package com.jiuyin.dianjing.ui.fragment.community;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.decoration.CustomDividerItemDecoration;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.PostModel;
import com.jiuyin.dianjing.model.ThumbModel;
import com.jiuyin.dianjing.ui.activity.community.CreatePostActivity;
import com.jiuyin.dianjing.ui.activity.community.PostDetailActivity;
import com.jiuyin.dianjing.ui.fragment.base.BaseRefreshFragment;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GENRE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_POST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TARGETID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.OSS_IMG_SCREEN_TOPIC;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_FIRST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_NUM;
import static com.jiuyin.dianjing.model.PostModel.OWN_POSTS;

/**
 * 帖子列表的Fragment
 */
public class PostFragment extends BaseRefreshFragment<PostModel> {
    @BindView(R.id.iv_edit)
    ImageView ivEdit;

    private static final String KEY_FORK_ID = "forkId";
    private static final String KEY_GENRE_TAG = "genreTag";
    private static final String KEY_GAME_TAG = "gameTag";

    private boolean status;
    private String mType;
    private String mGenre;
    private String mForkId;
    private String mGenreTag;
    private String mGameTag;
    /***
     *删除帖子的索引
     */
    private int mPosition = -1;

    public PostFragment() {
        super(PAGE_NUM);
    }

    /***
     *
     * @param type 搜索类型（0 热门 1 关注）
     * @param genre 帖子区域类型（0普通帖子 1高校电竞社 2线上俱乐部 3 城市网吧）
     * @param fork_id 分支主键,比如某一高校的id
     * @param genreTag 期望标签
     * @param gameTag 游戏标签即GameInfoModel的gameId
     * @return
     */
    public static PostFragment newInstance(String type, String genre, String fork_id, String genreTag, String gameTag) {
        PostFragment fragment = new PostFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        bundle.putString(KEY_GENRE, genre);
        bundle.putString(KEY_FORK_ID, fork_id);
        bundle.putString(KEY_GENRE_TAG, genreTag);
        bundle.putString(KEY_GAME_TAG, gameTag);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void setGameTag(String mGameTag) {
        this.mGameTag = mGameTag;
    }

    public void setGenreTag(String mGenreTag) {
        this.mGenreTag = mGenreTag;
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_post;
    }

    @Override
    protected void initData() {
        Bundle argumentsBundle = getArguments();
        if (null != argumentsBundle) {
            mType = argumentsBundle.getString(KEY_TYPE);
            mGenre = argumentsBundle.getString(KEY_GENRE);
            mForkId = argumentsBundle.getString(KEY_FORK_ID);
            mGenreTag = argumentsBundle.getString(KEY_GENRE_TAG);
            mGameTag = argumentsBundle.getString(KEY_GAME_TAG);
        }
        mAdapter = new BaseRecyclerAdapter<PostModel>(R.layout.item_post) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, PostModel model, int position) {
                if (null != model) {
                    TextView tvComment = holder.itemView.findViewById(R.id.tv_comment);
                    TextView tvClicked = holder.itemView.findViewById(R.id.tv_clicked);
                    CheckedTextView tvThumb = holder.itemView.findViewById(R.id.tv_thumb);
                    holder.text(R.id.tv_name, model.getNickname());
                    holder.text(R.id.tv_time, model.getCreate_time());
                    holder.text(R.id.tv_title, model.getTitle());
                    holder.text(R.id.tv_content, model.getContent());
                    holder.text(R.id.tv_tag_desire, model.getGenre_tag());
                    holder.text(R.id.tv_tag_game, model.getGame_tag());
                    tvComment.setText(model.getComment_num());
                    tvClicked.setText(model.getClick_num());
                    tvThumb.setText(model.getThumb_num());
                    tvThumb.setChecked(model.getIsThumb() == 1);
                    ImageView ivHead = holder.itemView.findViewById(R.id.iv_head);
                    if (model != null && model.getHeader() != null) {
                        StringBuilder url = new StringBuilder(model.getHeader());
                        url.append(OSS_IMG_SCREEN_TOPIC);
                        Glide.with(getActivity()).load(url.toString()).placeholder(R.drawable.img_header_placeholder).into(ivHead);
                    }
                    BGANinePhotoLayout ninePhotoLayout = holder.itemView.findViewById(R.id.layout_nine_grid);
                    ArrayList<String> photos = (ArrayList<String>) model.getPhoto();
                    if (photos != null) {
                        ArrayList<String> newPhotos = new ArrayList<>(photos.size());
                        for (String str : photos) {
                            StringBuilder sb = new StringBuilder(str);
                            sb.append(OSS_IMG_SCREEN_TOPIC);
                            newPhotos.add(sb.toString());
                        }
                        ninePhotoLayout.setDelegate(new BGANinePhotoLayout.Delegate() {
                            @Override
                            public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                                photoPreviewWrapper();
                            }

                            /**
                             * 图片预览
                             */
                            private void photoPreviewWrapper() {
                                File downloadDir = new File(Environment.getExternalStorageDirectory(), "jiuYin");
//                                BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder =
//                                        new BGAPhotoPreviewActivity.IntentBuilder(getActivity());
                                BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder = new BGAPhotoPreviewActivity.IntentBuilder(getActivity())
                                        .saveImgDir(downloadDir);
                                if (ninePhotoLayout.getItemCount() == 1) {
                                    // 预览单张图片
                                    photoPreviewIntentBuilder.previewPhoto(photos.get(ninePhotoLayout.getCurrentClickItemPosition()));
                                } else if (ninePhotoLayout.getItemCount() > 1) {
                                    // 预览多张图片
                                    photoPreviewIntentBuilder.previewPhotos(photos)
                                            .currentPosition(ninePhotoLayout.getCurrentClickItemPosition()); // 当前预览图片的索引
                                }
                                startActivity(photoPreviewIntentBuilder.build());
                            }

                            @Override
                            public void onClickExpand(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                                ninePhotoLayout.setIsExpand(true);
                                ninePhotoLayout.flushItems();
                            }
                        });
                        ninePhotoLayout.setData(newPhotos);
                    }

                    holder.itemView.findViewById(R.id.iv_more).setOnClickListener(v -> {
                        mPosition = position;
                        BottomSheetFragment.newInstance(model.getTopic_id(), model.getIsOneSelf().equals(OWN_POSTS), PostFragment.class.getSimpleName()).show(getChildFragmentManager(), "dialog");
                    });
                    tvThumb.setOnClickListener(v -> {
                        ApiResultCallback apiResultCallback = new ApiResultCallback() {
                            @Override
                            public void onSuccess(JsonObject data) {
                                ThumbModel thumbModel = new Gson().fromJson(data, ThumbModel.class);
                                tvThumb.setChecked(thumbModel.isThumb == 1);
                                tvThumb.setText(thumbModel.thumb_num);
                                tvThumb.setEnabled(true);
                                model.setThumb_num(thumbModel.thumb_num);
                                model.setIsThumb(thumbModel.isThumb);
                            }

                            @Override
                            public void onFail(String msg) {
                                ToastUtil.showShort(msg);
                                tvThumb.setEnabled(true);
                            }

                            @Override
                            public void onError(String msg) {
                                tvThumb.setEnabled(true);
                                LogUtil.log(msg);
                            }
                        };
                        HashMap<String, Object> params = new HashMap<>();
                        params.put(KEY_TOKEN, HelperApplication.getToken());
                        params.put(KEY_TARGETID, model.getTopic_id());
                        params.put(KEY_TYPE, tvThumb.isChecked() ? 0 : 1);
                        JSONObject json = new JSONObject(params);
                        tvThumb.setEnabled(false);
                        ServerApi.post(ApiEnum.APP_TOPIC_THUMB.getUrl(), json, null, progress, d -> addDisposable(d), apiResultCallback);
                    });
                }
            }
        };
        mAdapter.setOnItemClickListener((parent, view, position, id) -> {
            PostModel model = mAdapter.getItem(position);
            Bundle bundle = new Bundle();
            bundle.putSerializable(KEY_POST, model);
            goTargetActivity(PostDetailActivity.class, bundle);
        });
        mRcvPage.addItemDecoration(new CustomDividerItemDecoration(getContext()));//添加分割线
        mRcvPage.setItemAnimator(new DefaultItemAnimator());
        mRcvPage.setAdapter(mAdapter);
    }

    @Override
    protected void initView() {
        ivEdit.setOnClickListener(v -> {
            Intent intent = new Intent(getContext(), CreatePostActivity.class);
            intent.putExtra(KEY_GENRE, mGenre);//帖子区域类型（0普通 1 高校电竞社 ）
            if (mGenre.equals("1")) {
                intent.putExtra(KEY_FORK_ID, mForkId);
            }
            startActivity(intent);
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        if (status) {
            refresh();
            status = false;
        }
    }

    @Override
    public void fetchData() {
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, HelperApplication.getToken());
        params.put(KEY_PAGE_NUM, mPageNum);
        params.put(KEY_TYPE, mType);
        params.put(KEY_GENRE, mGenre);
        params.put(KEY_FORK_ID, mForkId);
        params.put(KEY_GENRE_TAG, mGenreTag);
        params.put(KEY_GAME_TAG, mGameTag);
        JSONObject jsonObject = new JSONObject(params);
        getApiHelper().appGetTopicList(jsonObject.toString(), data -> {
            dealWithSuccessInfo(data);
        });
    }

    public void refresh() {
        mPageNum = PAGE_FIRST;
        if (isVisible()) {
            mAdapter.clear();
            fetchData();
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshEvent event) {
        if (event.clazzName.equals(getClass().getSimpleName())) {
            status = true;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String mTargetId) {
        if (mTargetId.equals(getClass().getSimpleName())) {
            if (mPosition != -1) {
                mAdapter.remove(mAdapter.get(mPosition));
            }
        }
    }
}